#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Project: spd-sxmcc
"""
@author: lyndon
@time Created on 2018/10/30 16:54
@desc
"""

from __future__ import unicode_literals
from bratislava.conf.settings import log
from bratislava.thread_pool.BaseTask import BaseTask
from bratislava.thread_pool.task_executor import TaskExecutor


class TaskScheduler:

    def __init__(self, **kwargs):
        self.log = kwargs['log']

    def timer_scheduler(self, tasks, *args, **kwargs):
        """
        :desc 从数据库中抓取出需要调度的原始任务
        :param tasks:
        :param moniDate:
        :return: list[tasks]
        """
        schds = tasks
        return schds

    def call_back(self, trd):
        """
        执行的回调逻辑
        :param trd:
        :return:
        """
        stat, task_id, task_name = trd.result()
        print('任务 %s - %s 执行结果是:%s' % (task_id, task_name, stat))
        self.log.info('任务 %s - %s 执行结果是:%s', task_id, task_name, stat)

    def scheduler_main(self, tasks, **kwargs):
        """
        任务调度器
        :param tasks:
        :param moniDate:
        :return:
        """
        #moniDate = kwargs['moniDate'] if kwargs.has_key('moniDate') else "2019-02-18 00:59:59"  # 2.x
        moniDate = kwargs['moniDate'] if 'moniDate' in kwargs.keys() else "2019-02-18 00:59:59" # 3.x
        print(moniDate)
        schdl_tasks = self.timer_scheduler(tasks, moniDate)
        self.log.info('开始调度')
        taskExecutor = TaskExecutor(self.log)
        task_stat_results = taskExecutor.execute_task(schdl_tasks)
        return task_stat_results


if __name__ == '__main__':
    # 任务信息
    tasks = [('1', 'task1'), ('2', 'task2'), ('3', 'task3')]
    # 生成基本任务信息，如果需要实现自己的逻辑，建议继承BaseTask类，并覆盖运行逻辑task_run()方法
    tasks = (BaseTask(ot[0], ot[1]) for ot in tasks)
    # 实例化调度器
    taskScheduler = TaskScheduler(log=log)
    # 通过调度器发起异步调度线程，并获取结果到[]里
    task_results = taskScheduler.scheduler_main(tasks, moniDate="2019-02-18 00:59:59")
    # 回调执行结果
    for trd in task_results:
        taskScheduler.call_back(trd)
